<script setup lang="ts">
import { ref, onMounted, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import axios from 'axios';


const route = useRoute();
const router = useRouter();
const doctors = ref([]);
const loading = ref(true);
const showSortDropdown = ref(false);
const showLocationDropdown = ref(false);
const showFilterDropdown = ref(false);
const currentSort = ref('综合排序');
const currentLocation = ref('全国');
const provinces = ref([]);
const cities = ref([]);
const hotCities = ref([]);
const selectedProvince = ref(null);
const selectedSection = ref('热门城市');
const departmentName = ref(''); // 新增：用于存储科室名称


// Add filter state
const currentFilters = ref({
    price: null,
    title: null,
    city: null,
    ordering: ''
});

// Reset filters function
const resetFilters = () => {
    currentFilters.value = {
        price: null,
        title: null,
        city: null,
        ordering: ''
    };
    currentLocation.value = '全国';
    currentSort.value = '综合排序';
};

// Watch dropdowns to close others when one opens
watch(showSortDropdown, (newVal) => {
    if (newVal) {
        showLocationDropdown.value = false;
        showFilterDropdown.value = false;
    }
});

watch(showLocationDropdown, (newVal) => {
    if (newVal) {
        showSortDropdown.value = false;
        showFilterDropdown.value = false;
    }
});

watch(showFilterDropdown, (newVal) => {
    if (newVal) {
        showSortDropdown.value = false;
        showLocationDropdown.value = false;
    }
});

const sortOptions = [
    { label: '综合排序', value: '' },
    { label: '回答次数', value: '-consultation_count' },
    { label: '好评优先', value: 'rating' },
    { label: '响应时间', value: 'avg_response_time' },
    { label: '价格从低到高', value: 'consultation_price' },
    { label: '价格从高到低', value: '-consultation_price' }
];

const priceRanges = [
    { label: '19-39', min: 19, max: 39 },
    { label: '40-69', min: 40, max: 69 },
    { label: '70-99', min: 70, max: 99 },
    { label: '100以上', min: 100, max: null }
];

const doctorTitles = [
    { label: '主治医师', value: 1 },
    { label: '副主任医师', value: 2 },
    { label: '主任医师', value: 3 }
];

const fetchHotCities = async () => {
    try {
        const response = await axios.get('http://127.0.0.1:8000/doctor/city/0/');
        hotCities.value = response.data;
    } catch (error) {
        console.error('Error fetching hot cities:', error);
    }
};

const fetchDoctors = async () => {
    try {
        const departmentId = route.params.departmentId;
        const response = await axios.get(`http://127.0.0.1:8000/doctor/doctor/${departmentId}/`, {
            params: currentFilters.value
        });
        doctors.value = response.data;
        departmentName.value = response.data[0]?.department || ''; // 新增：获取科室名称
    } catch (error) {
        console.error('Error fetching doctors:', error);
    } finally {
        loading.value = false;
    }
};

const fetchProvinces = async () => {
    try {
        const response = await axios.get('http://127.0.0.1:8000/doctor/province/');
        provinces.value = response.data;
    } catch (error) {
        console.error('Error fetching provinces:', error);
    }
};

const fetchCities = async (provinceId) => {
    try {
        const response = await axios.get(`http://127.0.0.1:8000/doctor/city/${provinceId}/`);
        cities.value = response.data;
    } catch (error) {
        console.error('Error fetching cities:', error);
    }
};

const handleLocationSelect = async (province) => {
    selectedProvince.value = province;
    selectedSection.value = province.name;
    await fetchCities(province.id);
};

const handleHotCitySelect = () => {
    selectedSection.value = '热门城市';
    fetchHotCities();
};

const handleCitySelect = (city) => {
    currentLocation.value = city.name;
    showLocationDropdown.value = false;
    currentFilters.value = {
        ...currentFilters.value,
        city: city.id
    };
    fetchDoctors();
};

const handleSort = (option) => {
    currentSort.value = option.label;
    showSortDropdown.value = false;

    if (option.label === '综合排序') {
        resetFilters();
    } else {
        currentFilters.value = {
            ...currentFilters.value,
            ordering: option.value
        };
    }
    fetchDoctors();
};

const handleFilter = (type, value) => {
    if (type === 'price') {
        currentFilters.value = {
            ...currentFilters.value,
            consultation_price_min: value.min,
            consultation_price_max: value.max
        };
    } else if (type === 'title') {
        currentFilters.value = {
            ...currentFilters.value,
            title: value
        };
    }
    showFilterDropdown.value = false;
    fetchDoctors();
};

const navigateToDoctor = (doctorId) => {
    // router.push(`/doctor/${doctorId}`);
    window.open(`/doctor/${doctorId}`, '_blank');
};







onMounted(() => {
    fetchDoctors();
    fetchProvinces();
    fetchHotCities();
    
});
</script>

<template>


    <div class="doctor-list-container">
        <div class="department-header" v-if="departmentName">
            <h2>{{ departmentName }}</h2>
        </div>

        <div class="filter-header">
            <div class="filter-buttons">
                <div class="dropdown-container">
                    <button @click="showSortDropdown = !showSortDropdown" class="dropdown-button">
                        {{ currentSort }}
                        <span class="arrow" :class="{ 'arrow-up': showSortDropdown }">▼</span>
                    </button>
                    <div v-if="showSortDropdown" class="dropdown-menu">
                        <div v-for="option in sortOptions" :key="option.value" @click="handleSort(option)"
                            class="dropdown-item">
                            {{ option.label }}
                        </div>
                    </div>
                </div>

                <div class="dropdown-container">
                    <button @click="showLocationDropdown = !showLocationDropdown" class="dropdown-button">
                        {{ currentLocation }}
                        <span class="arrow" :class="{ 'arrow-up': showLocationDropdown }">▼</span>
                    </button>
                    <div v-if="showLocationDropdown" class="location-dropdown">
                        <div class="provinces-list">
                            <div class="province-item hot-cities" @click="handleHotCitySelect()"
                                :class="{ active: selectedSection === '热门城市' }">
                                热门城市
                            </div>
                            <div v-for="province in provinces" :key="province.id"
                                @click="handleLocationSelect(province)"
                                :class="['province-item', { active: selectedSection === province.name }]">
                                {{ province.name }}
                            </div>
                        </div>
                        <div class="cities-list">
                            <template v-if="selectedSection === '热门城市'">
                                <div v-for="city in hotCities" :key="city.id" @click="handleCitySelect(city)"
                                    class="city-item">
                                    {{ city.name }}
                                </div>
                            </template>
                            <template v-else>
                                <div v-for="city in cities" :key="city.id" @click="handleCitySelect(city)"
                                    class="city-item">
                                    {{ city.name }}
                                </div>
                            </template>
                        </div>
                    </div>
                </div>

                <div class="dropdown-container">
                    <button @click="showFilterDropdown = !showFilterDropdown" class="dropdown-button">
                        筛选
                        <span class="arrow" :class="{ 'arrow-up': showFilterDropdown }">▼</span>
                    </button>
                    <div v-if="showFilterDropdown" class="filter-dropdown">
                        <div class="filter-section">
                            <h3>价格区间</h3>
                            <div class="filter-options">
                                <button v-for="range in priceRanges" :key="range.label"
                                    @click="handleFilter('price', range)" :class="['filter-option', {
                                        'active': currentFilters.consultation_price_min === range.min &&
                                            currentFilters.consultation_price_max === range.max
                                    }]">
                                    {{ range.label }}
                                </button>
                            </div>
                        </div>
                        <div class="filter-section">
                            <h3>医生职称</h3>
                            <div class="filter-options">
                                <button v-for="title in doctorTitles" :key="title.value"
                                    @click="handleFilter('title', title.value)"
                                    :class="['filter-option', { 'active': currentFilters.title === title.value }]">
                                    {{ title.label }}
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div v-if="loading" class="loading">加载中...</div>
        <div v-else class="doctors-list">
            <div v-for="doctor in doctors" :key="doctor.id" class="doctor-card" @click="navigateToDoctor(doctor.id)">
                <div class="doctor-info">
                    <img :src="doctor.avatar" :alt="doctor.name" class="doctor-avatar">
                    <div class="doctor-details">
                        <div class="name-title">
                            <h3>{{ doctor.name }}</h3>
                            <span class="title">{{ doctor.get_title_display }}</span>
                        </div>
                        <div class="hospital-info">
                            <span>{{ doctor.department }}</span>
                            <span>{{ doctor.hospital }}</span>
                        </div>
                        <div class="specialty">
                            <span>擅长：</span>
                            <div v-html="doctor.specialty" class="specialty-content"></div>
                        </div>
                        <div class="rating-info">
                            <span class="stars">★★★★★</span>
                            <span class="rating">{{ doctor.rating }}</span>
                            <span class="consultation-count">{{ doctor.consultation_count }}次问诊</span>
                        </div>
                    </div>
                    <div class="action-area">
                        <div class="price">¥{{ doctor.consultation_price }}</div>
                        <button class="consult-button">问医生</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<style scoped>
.department-header {
    /* text-align: center; */
    padding: 15px 0;
    font-size: 24px;
    font-weight: bold;
    color: #00b38a;
    border-bottom: 2px solid #00b38a;
}

.doctor-list-container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 20px;
}

.filter-header {
    padding: 15px 0;
    border-bottom: 1px solid #f0f0f0;
    position: sticky;
    top: 0;
    background: white;
    z-index: 100;
}

.filter-buttons {
    display: flex;
    justify-content: flex-start;
    width: 100%;
    max-width: 360px;
}

.dropdown-container {
    flex: 1;
    position: relative;
    margin-right: 10px;
}

.dropdown-container:last-child {
    margin-right: 0;
}

.dropdown-button {
    width: 100%;
    padding: 6px 12px;
    border: 1px solid #e8e8e8;
    background: #fff;
    color: #333;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    border-radius: 4px;
    transition: all 0.3s ease;
}

.dropdown-button:hover {
    border-color: #00b38a;
    color: #00b38a;
}

.arrow {
    font-size: 12px;
    color: #999;
    transition: transform 0.3s ease;
}

.arrow-up {
    transform: rotate(180deg);
}

.dropdown-container:hover .arrow {
    color: #00b38a;
}

.dropdown-menu,
.location-dropdown,
.filter-dropdown {
    position: absolute;
    top: calc(100% + 5px);
    left: 0;
    background: white;
    border: 1px solid #e8e8e8;
    border-radius: 4px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
    z-index: 1000;
}

.dropdown-item {
    padding: 10px 16px;
    font-size: 14px;
    color: #333;
    cursor: pointer;
    transition: all 0.2s ease;
}

.dropdown-item:hover {
    background: #f6f6f6;
    color: #00b38a;
}

.location-dropdown {
    display: flex;
    width: 460px;
}

.provinces-list {
    width: 140px;
    border-right: 1px solid #f0f0f0;
    background: #fafafa;
}

.cities-list {
    flex: 1;
    background: #fff;
}

.provinces-list,
.cities-list {
    max-height: 400px;
    overflow-y: auto;
}

.province-item,
.city-item {
    padding: 12px 16px;
    font-size: 14px;
    color: #333;
    cursor: pointer;
    transition: all 0.2s ease;
}

.province-item {
    position: relative;
}

.province-item.active {
    color: #00b38a;
    background: #fff;
}

.province-item.active::after {
    content: '';
    position: absolute;
    right: 0;
    top: 0;
    bottom: 0;
    width: 2px;
    background: #00b38a;
}

.province-item:hover,
.city-item:hover {
    color: #00b38a;
    background: #f6f6f6;
}

.filter-dropdown {
    width: 320px;
    padding: 16px;
}

.filter-section {
    margin-bottom: 20px;
}

.filter-section:last-child {
    margin-bottom: 0;
}

.filter-section h3 {
    margin-bottom: 12px;
    font-size: 14px;
    color: #333;
    font-weight: 500;
}

.filter-options {
    display: flex;
    flex-wrap: wrap;
    gap: 12px;
}

.filter-option {
    padding: 6px 16px;
    border: 1px solid #e8e8e8;
    border-radius: 16px;
    background: #fff;
    font-size: 14px;
    color: #333;
    cursor: pointer;
    transition: all 0.2s ease;
}

.filter-option:hover {
    border-color: #00b38a;
    color: #00b38a;
}

.filter-option.active {
    background: #00b38a;
    color: white;
    border-color: #00b38a;
}

.doctors-list {
    margin-top: 20px;
}

.doctor-card {
    padding: 20px;
    border-bottom: 1px solid #eee;
    cursor: pointer;
    transition: all 0.3s ease;
}

.doctor-card:hover {
    background: #f9f9f9;
}

.doctor-info {
    display: flex;
    gap: 20px;
}

.doctor-avatar {
    width: 80px;
    height: 80px;
    border-radius: 50%;
    object-fit: cover;
}

.doctor-details {
    flex: 1;
}

.name-title {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 8px;
}

.name-title h3 {
    margin: 0;
    font-size: 18px;
}

.title {
    color: #666;
    font-size: 14px;
}

.hospital-info {
    color: #666;
    margin-bottom: 8px;
}

.specialty {
    display: inline-block;
    color: #666;
    margin-bottom: 8px;
    align-items: flex-start;
}

.specialty-content {
    display: inline-block;
    flex: 1;
}

.rating-info {
    display: flex;
    align-items: center;
    gap: 10px;
}

.stars {
    color: #ffb800;
}

.rating {
    color: #ffb800;
    font-weight: bold;
}

.consultation-count {
    color: #666;
}

.action-area {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: flex-end;
    gap: 10px;
    min-width: 120px;
}

.price {
    color: #00b38a;
    font-size: 20px;
    font-weight: bold;
}

.consult-button {
    padding: 8px 20px;
    background: #00b38a;
    color: white;
    border: none;
    border-radius: 20px;
    cursor: pointer;
    transition: all 0.3s ease;
}

.consult-button:hover {
    background: #009b76;
}

.loading {
    text-align: center;
    padding: 40px;
    color: #666;
}
</style>